package top.malaoshi.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;


public class DbSessionImpl implements DbSession {

    private Db db;

    public DbSessionImpl(Db db) {
        this.db = db;
    }

    /**
     * 如果是自动提交，那么就自动关闭连接
     * @throws SQLException
     */
    private void autoClose() throws SQLException {

        if(db.getConnection().getAutoCommit()){
            db.close();
            db.setConnection(null);
        }
    }

    @Override
    public List<Record> query(String sql, Object... objects) throws SQLException {
        try{
            List<Record> list = db.query(sql, objects);
            return list;
        }finally {
            autoClose();
        }
    }

    @Override
    public <E> List<E> query(Class clazz, String sql, Object... params) throws SQLException  {
        try{
            List list = db.query(clazz, sql, params);
            return list;
        }finally {
            autoClose();
        }
    }

    @Override
    public int update(String sql, Object... objects) throws SQLException {
        try{
            int i = db.update(sql, objects);
            return i;
        }finally {
            autoClose();
        }
    }

    @Override
    public int updateTag(String sql, Object obj) throws SQLException{
        try{
            int i = db.updateTag(sql, obj);
            return i;
        }finally {
            autoClose();
        }
    }

    @Override
    public List<Record> queryTag(String sql, Object obj) throws SQLException{
        try{
            List<Record> list = db.queryTag(sql, obj);
            return list;
        }finally {
            autoClose();
        }
    }

    @Override
    public <E> List<E> queryTag(Class clazz, String sql, Object obj) throws SQLException{
        try{
            List list = db.queryTag(clazz,sql, obj);
            return list;
        }finally {
            autoClose();
        }
    }

    @Override
    public void close() throws SQLException {
        db.close();
    }

    @Override
    public void commit() throws SQLException {
        db.commit();
    }

    @Override
    public void rollback() throws SQLException {
        db.rollback();
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        db.getConnection().setAutoCommit(autoCommit);
    }

    @Override
    public Connection getConnection() {
        return db.getConnection();
    }
}
